# 100. 相同的树

function TreeNode(val, left, right) {
  this.val = val === undefined ? 0 : val;
  this.left = left === undefined ? null : left;
  this.right = right === undefined ? null : right;
}
var isSameTree = function(p, q) {
  let isSame = true;
  function inorder(root1, root2) {
    if (!root1 && !root2) return;
    if (!isSame) return;
    if (!root1) return (isSame = false);
    if (!root2) return (isSame = false);
    if (root1.val !== root2.val) return (isSame = false);
    inorder(root1.left, root2.left);
    inorder(root1.right, root2.right);
  }
  inorder(p, q);

  return isSame;
};

var isSameTree = function(p, q) {
  if (!p && !q) return true;

  if (
    p &&
    q &&
    p.val === q.val &&
    isSameTree(p.left, q.left) &&
    isSameTree(p.right, q.right)
  ) {
    return true;
  }
  return false;
};

const p = {
  val: 1,
  left: {
    val: 2,
  },
  right: {
    val: 3,
  },
};

const q = {
  val: 1,
  left: {
    val: 2,
  },
  right: {
    val: 3,
  },
};
console.log(isSameTree(p, q));

const p1 = {
  val: 1,
  left: {
    val: 1,
  },
};

const q1 = {
  val: 1,
  right: {
    val: 1,
  },
};
console.log(isSameTree(p1, q1));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
Last Updated: 7/4/2023, 6:50:39 PM